package com.aps.demo.adapter.impl;

import com.aps.common.model.EquipmentAbandoned;
import com.aps.common.model.OrderAbandoned;
import com.aps.demo.adapter.ModelAdapter;
import com.aps.demo.model.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

// 导入公共模块中的模型类
import com.aps.common.model.APSProductModel;

import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 汽车行业适配器
 * 专门处理汽车零部件生产的参数模型转换
 */
@Slf4j
@Component("automotiveAdapter")
public class AutomotiveAdapter implements ModelAdapter {
    
    private static final String INDUSTRY_TYPE = "AUTOMOTIVE";
    private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    
    @Override
    public APSProductModel adapt(ProductionData sourceData) {
        log.info("开始适配汽车行业生产数据...");
        
        APSProductModel model = new APSProductModel();
        
        // 转换产品信息
        model.setProduct(convertProduct(sourceData.getProductInfo()));
        
        // 转换订单信息
        model.setOrders(convertOrders(sourceData.getOrders()));
        
        // 转换工艺路线
        model.setOperations(convertOperations(sourceData.getProcessFlow()));
        
        // 转换资源信息
        model.setResources(convertResources(sourceData.getEquipment(), sourceData.getPersonnel()));
        
        // 转换约束条件
        model.setConstraints(convertConstraints(sourceData.getConstraints()));
        
        // 设置元数据
        model.setMetadata(createMetadata(sourceData));
        
        log.info("汽车行业生产数据适配完成");
        return model;
    }
    
    @Override
    public ValidationResult validate(APSProductModel model) {
        log.info("开始验证APS参数模型...");
        
        List<String> errors = new ArrayList<>();
        
        // 验证产品信息
        if (model.getProduct() == null) {
            errors.add("产品信息不能为空");
        }
        
        // 验证订单信息
        if (model.getOrders() == null || model.getOrders().isEmpty()) {
            errors.add("订单信息不能为空");
        }
        
        // 验证工艺路线
        if (model.getOperations() == null || model.getOperations().isEmpty()) {
            errors.add("工艺路线不能为空");
        }
        
        // 验证资源信息
        if (model.getResources() == null) {
            errors.add("资源信息不能为空");
        } else {
            if (model.getResources().getEquipment() == null || model.getResources().getEquipment().isEmpty()) {
                errors.add("设备资源不能为空");
            }
            if (model.getResources().getPersonnel() == null || model.getResources().getPersonnel().isEmpty()) {
                errors.add("人员资源不能为空");
            }
        }
        
        // 验证约束条件
        if (model.getConstraints() == null) {
            errors.add("约束条件不能为空");
        }
        
        if (errors.isEmpty()) {
            log.info("APS参数模型验证通过");
            return ValidationResult.success();
        } else {
            log.warn("APS参数模型验证失败: {}", String.join(", ", errors));
            return ValidationResult.failure(errors.toArray(new String[0]));
        }
    }
    
    @Override
    public Object transform(APSProductModel model, String targetFormat) {
        log.info("开始转换模型到格式: {}", targetFormat);
        
        switch (targetFormat.toUpperCase()) {
            case "JSON":
                return convertToJson(model);
            case "XML":
                return convertToXml(model);
            default:
                throw new UnsupportedOperationException("不支持的转换格式: " + targetFormat);
        }
    }
    
    @Override
    public String getSupportedIndustry() {
        return INDUSTRY_TYPE;
    }
    
    // 转换方法实现
    private APSProductModel.Product convertProduct(com.aps.common.model.ProductInfo productInfo) {
        APSProductModel.Product product = new APSProductModel.Product();
        product.setId(productInfo.getProductId());
        product.setName(productInfo.getProductName());
        product.setCategory(productInfo.getProductCategory());
        product.setMaterial(productInfo.getMaterial());
        product.setAnnualDemand(productInfo.getAnnualDemand());
        return product;
    }
    
    private List<APSProductModel.ProductionOrder> convertOrders(List<OrderAbandoned> orders) {
        return orders.stream().map(order -> {
            APSProductModel.ProductionOrder productionOrder = new APSProductModel.ProductionOrder();
            productionOrder.setId(order.getOrderId());
            productionOrder.setCustomerName(order.getCustomerName());
            productionOrder.setCustomerLevel(order.getCustomerLevel());
            productionOrder.setProductModel(order.getProductModel());
            productionOrder.setQuantity(order.getQuantity());
            productionOrder.setDeliveryDate(order.getDeliveryDate().format(DATE_FORMATTER));
            productionOrder.setPriority(order.getPriority());
            productionOrder.setOrderAmount(order.getOrderAmount().doubleValue());
            return productionOrder;
        }).collect(Collectors.toList());
    }
    
    private List<APSProductModel.Operation> convertOperations(List<ProcessStep> processSteps) {
        return processSteps.stream().map(step -> {
            APSProductModel.Operation operation = new APSProductModel.Operation();
            operation.setId(step.getOperationId());
            operation.setName(step.getOperationName());
            operation.setSequence(step.getSequence());
            operation.setEquipmentType(step.getEquipmentType());
            operation.setStandardTime(step.getStandardTime().getValue());
            operation.setSetupTime(step.getSetupTime().getValue());
            operation.setPersonnelRequirement(step.getPersonnelRequirement());
            operation.setQualityRequirement(step.getQualityRequirement());
            return operation;
        }).collect(Collectors.toList());
    }
    
    private APSProductModel.Resources convertResources(List<EquipmentAbandoned> equipment, List<Personnel> personnel) {
        APSProductModel.Resources resources = new APSProductModel.Resources();
        
        // 转换设备资源
        List<APSProductModel.EquipmentResource> equipmentResources = equipment.stream().map(eq -> {
            APSProductModel.EquipmentResource resource = new APSProductModel.EquipmentResource();
            resource.setId(eq.getEquipmentId());
            resource.setName(eq.getEquipmentName());
            resource.setType(eq.getEquipmentType());
            resource.setDailyCapacity(eq.getDailyCapacity().getValue());
            resource.setEfficiencyFactor(eq.getEfficiencyFactor());
            resource.setMaintenanceSchedule(eq.getMaintenanceSchedule());
            resource.setStatus(eq.getStatus());
            return resource;
        }).collect(Collectors.toList());
        resources.setEquipment(equipmentResources);
        
        // 转换人员资源
        List<APSProductModel.PersonnelResource> personnelResources = personnel.stream().map(p -> {
            APSProductModel.PersonnelResource resource = new APSProductModel.PersonnelResource();
            resource.setId(p.getPersonnelId());
            resource.setName(p.getName());
            resource.setJobType(p.getJobType());
            resource.setSkillLevel(p.getSkillLevel());
            resource.setDailyWorkHours(p.getDailyWorkHours().getValue());
            resource.setOperableEquipment(p.getOperableEquipment());
            resource.setStatus(p.getStatus());
            return resource;
        }).collect(Collectors.toList());
        resources.setPersonnel(personnelResources);
        
        return resources;
    }
    
    private APSProductModel.Constraints convertConstraints(Constraint constraints) {
        APSProductModel.Constraints apsConstraints = new APSProductModel.Constraints();
        
        // 转换硬约束
        if (constraints.getHardConstraints() != null) {
            List<APSProductModel.HardConstraint> hardConstraints = constraints.getHardConstraints().stream().map(hc -> {
                APSProductModel.HardConstraint constraint = new APSProductModel.HardConstraint();
                constraint.setId(hc.getConstraintId());
                constraint.setType(hc.getConstraintType());
                constraint.setDescription(hc.getDescription());
                constraint.setPriority(hc.getPriority());
                return constraint;
            }).collect(Collectors.toList());
            apsConstraints.setHardConstraints(hardConstraints);
        }
        
        // 转换软约束
        if (constraints.getSoftConstraints() != null) {
            List<APSProductModel.SoftConstraint> softConstraints = constraints.getSoftConstraints().stream().map(sc -> {
                APSProductModel.SoftConstraint constraint = new APSProductModel.SoftConstraint();
                constraint.setId(sc.getConstraintId());
                constraint.setType(sc.getConstraintType());
                constraint.setDescription(sc.getDescription());
                constraint.setWeight(sc.getWeight());
                return constraint;
            }).collect(Collectors.toList());
            apsConstraints.setSoftConstraints(softConstraints);
        }
        
        return apsConstraints;
    }
    
    private Map<String, Object> createMetadata(ProductionData sourceData) {
        Map<String, Object> metadata = new HashMap<>();
        metadata.put("industry", INDUSTRY_TYPE);
        metadata.put("adaptationTime", new Date());
        metadata.put("dataSource", "JSON");
        metadata.put("version", "1.0");
        return metadata;
    }
    
    private String convertToJson(APSProductModel model) {
        return "JSON格式转换待实现";
    }
    
    private String convertToXml(APSProductModel model) {
        return "XML格式转换待实现";
    }
} 